package org.mx.dal.hibernate.single.service;

import org.mx.dal.hibernate.single.entity.AccountEntity;
import org.mx.dal.hibernate.single.entity.OrgEntity;
import org.mx.dal.hibernate.single.entity.RoleEntity;
import org.mx.dal.service.GeneralDictAccessor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("javadoc")
@Component
public class LazyEntityOperateService {
	private GeneralDictAccessor accessor;

	public LazyEntityOperateService(@Qualifier("generalDictAccessor") GeneralDictAccessor accessor) {
		super();
		this.accessor = accessor;
	}
	
	@Transactional(readOnly = true)
	public OrgEntity getOrgById(String id) {
		OrgEntity org = accessor.getById(id, OrgEntity.class);
		if (org != null) {
			iterateParent(org);
			iterateChild(org);
		}
		return org;
	}
	
	@Transactional(readOnly = true)
	public OrgEntity getOrgByCode(String code) {
		OrgEntity org = accessor.getByCode(code, OrgEntity.class);
		if (org != null) {
			iterateParent(org);
			iterateChild(org);
		}
		return org;
	}
	
	private void iterateParent(OrgEntity org) {
		if (org != null && org.getParent() != null) {
			org.getParent().getChildren().size();
			iterateParent(org.getParent());
		}
	}
	
	private void iterateChild(OrgEntity org) {
		if (org != null && org.getChildren() != null) {
			org.getChildren().size();
			org.getChildren().forEach(o -> iterateChild(o));
		}
	}

	@Transactional(readOnly = true)
	public AccountEntity getAccountById(String id) {
		AccountEntity account = accessor.getById(id, AccountEntity.class);
		if (account != null) {
			account.getRoles().size();
		}
		return account;
	}

	@Transactional(readOnly = true)
	public AccountEntity getAccountByCode(String code) {
		AccountEntity account = accessor.getByCode(code, AccountEntity.class);
		if (account != null) {
			account.getRoles().size();
		}
		return account;
	}

	@Transactional(readOnly = true)
	public RoleEntity getRoleById(String id) {
		RoleEntity role = accessor.getById(id, RoleEntity.class);
		if (role != null) {
			role.getAccounts().size();
		}
		return role;
	}

	@Transactional(readOnly = true)
	public RoleEntity getRoleByCode(String code) {
		RoleEntity role = accessor.getByCode(code, RoleEntity.class);
		if (role != null) {
			role.getAccounts().size();
		}
		return role;
	}
}
